import HandleBtn from '@/components/HandleBar/btn';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  historyDataControllerClusterHistoryData,
  historyDataControllerHistoryDataExport as exportDataReport,
} from '@/services/ess/historicalData';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { downloadFetch } from '@/utils/downloadFile';
import { Link, useIntl } from '@umijs/max';
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { getHiddenColumnKeysFromRecords, hideEmptyDataColumns } from '../../utils';

interface Props {
  tabIndex?: string;
  deviceCode?: string;
  deviceType?: string;
  areaId?: string;
  selectedKeys?: string[];
}

const BatteryClusterInfo: React.FC<Props> = ({ deviceCode, deviceType, areaId, selectedKeys }) => {
  const intl = useIntl(); // 获取国际化实例
  const [data, setData] = useState<API.ClusterPageDataDTO[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    current: 1,
    pageSize: 20,
    startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
    endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
  });
  const chargeStatusRef = useRef<{ [key: string]: string }>({});
  const deviceOnlineStatusRef = useRef<{ [key: string]: string }>({});
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);

  useEffect(() => {
    const fetchChargeStatus = async () => {
      const statusDict = await fetchDictInfo(DATABASE_TYPE_ENUM.CHARGE_STATUS);
      // 假设 fetchDictInfo 返回的结构是 [{ label: string, value: string }]
      const simplifiedStatusDict = Object.fromEntries(
        statusDict.map(({ label, value }) => [value, label]),
      );
      chargeStatusRef.current = simplifiedStatusDict;
    };

    const fetchDeviceOnlineStatus = async () => {
      const statusDict = await fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS);
      // 假设 fetchDictInfo 返回的结构是 [{ label: string, value: string }]
      const simplifiedStatusDict = Object.fromEntries(
        statusDict.map(({ label, value }) => [value, label]),
      );
      deviceOnlineStatusRef.current = simplifiedStatusDict;
    };

    fetchChargeStatus();
    fetchDeviceOnlineStatus();
  }, []);

  const correctColumn: ProColumns = {
    title: intl.formatMessage({ id: 'data.available' }),
    dataIndex: 'correct',
    valueType: 'select',
    valueEnum: {
      1: {
        text: intl.formatMessage({ id: 'data.effective' }),
      },
      0: {
        text: intl.formatMessage({ id: 'data.invalid' }),
      },
    },
    render: (_, record) => {
      const value = record.correct;
      return value === 0
        ? intl.formatMessage({ id: 'data.invalid' })
        : value === 1
        ? intl.formatMessage({ id: 'data.effective' })
        : '-';
    },
  };

  const clusterColumns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }), // 序号
      key: 'index',
      valueType: 'index',
      width: 60,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({ id: 'data.acquisitionTime' }), // 采集时间
      dataIndex: 'collectTime',
      key: 'collectTime',
      valueType: 'dateTimeRange',
      width: 200,
      initialValue: [dayjs().startOf('day'), dayjs()],
      render: (_, record) => {
        return <span>{record.collectTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
          };
        },
      },
      fieldProps: {
        onCalendarChange: (dates: [Dayjs, Dayjs]) => {
          if (dates && dates.length === 2) {
            const [start, end] = dates;
            if (dayjs(end).diff(start, 'day') > 31) {
              message.warning(intl.formatMessage({ id: 'data.sDays' }));
            }
          }
        },
        disabledDate: (current: Dayjs | null) => {
          return current && current > dayjs().endOf('day');
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'data.reportingTime' }), // 上报时间
      dataIndex: 'reportTime',
      key: 'reportTime',
      hideInSearch: true,
      width: 200,
      initialValue: [dayjs().startOf('day'), dayjs()],
      render: (_, record) => {
        return <span>{record.reportTime}</span>;
      },
    },
    correctColumn,
    {
      title: intl.formatMessage({ id: 'data.batteryBoxName' }), // 电池箱名称
      dataIndex: 'batteryBoxName',
      key: 'batteryBoxName',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.batteryStackName' }), // 电池堆名称
      dataIndex: 'batteryStackName',
      key: 'batteryStackName',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.batteryClusterName' }), // 电池簇名称
      dataIndex: 'batteryClusterName',
      key: 'batteryClusterName',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.bcmsOnlineStatus' }), // BCMS在线状态
      dataIndex: 'bcmsOnlineStatus',
      key: 'bcmsOnlineStatus',
      hideInSearch: true,
      width: 150,
      render: (_, record) => {
        return (
          <span>
            {deviceOnlineStatusRef.current[record.bcmsOnlineStatus] || record.bcmsOnlineStatus}
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'data.bcuOnlineStatus' }), // BCU在线状态
      dataIndex: 'bcuOnlineStatus',
      key: 'bcuOnlineStatus',
      hideInSearch: true,
      width: 150,
      render: (_, record) => {
        return (
          <span>
            {deviceOnlineStatusRef.current[record.bcuOnlineStatus] || record.bcuOnlineStatus}
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'data.chargeDischargeStatus' }), // 充放电状态
      dataIndex: 'chargeDischargeStatus',
      key: 'chargeDischargeStatus',
      hideInSearch: true,
      width: 150,
      render: (_, record) => {
        return (
          <span>
            {chargeStatusRef.current[record.chargeDischargeStatus] || record.chargeDischargeStatus}
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'data.contactorStatus' }), // 接触器状态
      dataIndex: 'contactorStatus',
      key: 'contactorStatus',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.gcbFault' }), // 总断路器故障
      dataIndex: 'totalBreakerFault',
      key: 'totalBreakerFault',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.balancedMode' }), // 均衡模式
      dataIndex: 'balanceMode',
      key: 'balanceMode',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.balancedMModeEnable' }), // 均衡手动模式使能
      dataIndex: 'balanceManualModeEnable',
      key: 'balanceManualModeEnable',
      hideInSearch: true,
      width: 150,
      render: (_, record) => {
        return (
          <span>
            {record.balanceManualModeEnable
              ? intl.formatMessage({ id: 'data.enable' })
              : intl.formatMessage({ id: 'data.disable' })}
          </span>
        );
      },
    },
    // {
    //   title: intl.formatMessage({ id: 'data.balancedStatus' }), // 均衡状态
    //   dataIndex: 'balanceStatus',
    //   key: 'balanceStatus',
    //   hideInSearch: true,
    //   width: 150,
    // },
    {
      title: intl.formatMessage({ id: 'data.fanStatus' }), // 风扇状态
      dataIndex: 'fanStatus',
      key: 'fanStatus',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.fanFault' }), // 风扇故障
      dataIndex: 'fanFault',
      key: 'fanFault',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.powerLimitStatusWord' }), // 限功率状态字
      dataIndex: 'powerLimitStatus',
      key: 'powerLimitStatus',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.alarmStatusWord' }), // 告警状态字
      dataIndex: 'alarmStatus',
      key: 'alarmStatus',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.protectionStatusWord' }), // 保护状态字
      dataIndex: 'protectionStatus',
      key: 'protectionStatus',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.chargePowerLimits' }), // 充电功率限值
      dataIndex: 'chargePowerLimit',
      key: 'chargePowerLimit',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.dischargePowerLimits' }), // 放电功率限值
      dataIndex: 'dischargePowerLimit',
      key: 'dischargePowerLimit',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.clusterBMUAvgVoltage' }), // 簇BMU平均电压(V)
      dataIndex: 'clusterBMUAverageVoltage',
      key: 'clusterBMUAverageVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.avgVoltageOfCluster' }), // 簇单体平均电压(V)
      dataIndex: 'clusterCellAverageVoltage',
      key: 'clusterCellAverageVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.avgTempOfCluster' }), // 簇单体平均温度(℃)
      dataIndex: 'clusterCellAverageTemperature',
      key: 'clusterCellAverageTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.deltaVmaxOfCluster' }), // 簇单体最大压差(V)
      dataIndex: 'clusterCellMaxVoltageDifference',
      key: 'clusterCellMaxVoltageDifference',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.deltaTmaxOfCluster' }), // 簇单体最大温差(℃)
      dataIndex: 'clusterCellMaxTemperatureDifference',
      key: 'clusterCellMaxTemperatureDifference',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.vmaxOfCluster' }), // 簇单体最大电压(V)
      dataIndex: 'clusterCellMaxVoltage',
      key: 'clusterCellMaxVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfVmaxPacketForCluster' }), // 簇单体最大电压包索引
      dataIndex: 'clusterCellMaxVoltagePackIndex',
      key: 'clusterCellMaxVoltagePackIndex',
      hideInSearch: true,
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinVmaxPacketOfCluster' }), // 簇单体最大电压包内索引
      dataIndex: 'clusterCellMaxVoltagePackInnerIndex',
      key: 'clusterCellMaxVoltagePackInnerIndex',
      hideInSearch: true,
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'data.secondLargestVoltageOfCluster' }), // 簇单体第二大电压(V)
      dataIndex: 'clusterCellSecondMaxVoltage',
      key: 'clusterCellSecondMaxVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfSecondLargestVoltagePacket' }), // 簇单体第二电压包索引
      dataIndex: 'clusterCellSecondMaxVoltagePackIndex',
      key: 'clusterCellSecondMaxVoltagePackIndex',
      hideInSearch: true,
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinSecondLargestVoltagePacket' }), // 簇单体第二电压包内索引
      dataIndex: 'clusterCellSecondMaxVoltagePackInnerIndex',
      key: 'clusterCellSecondMaxVoltagePackInnerIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.vminOfClusters' }), // 簇单体最小电压(V)
      dataIndex: 'clusterCellMinVoltage',
      key: 'clusterCellMinVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfVminPacketForCluster' }), // 簇单体最小电压包索引
      dataIndex: 'clusterCellMinVoltagePackIndex',
      key: 'clusterCellMinVoltagePackIndex',
      hideInSearch: true,
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinVminPacketOfCluster' }), // 簇单体最小电压包内索引
      dataIndex: 'clusterCellMinVoltagePackInnerIndex',
      key: 'clusterCellMinVoltagePackInnerIndex',
      hideInSearch: true,
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'data.secondSmallestVoltageOfCluster' }), // 簇单体第二小电压(V)
      dataIndex: 'clusterCellSecondMinVoltage',
      key: 'clusterCellSecondMinVoltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfSecondSmallestVoltagePacket' }), // 簇单体第二小电压包索引
      dataIndex: 'clusterCellSecondMinVoltagePackIndex',
      key: 'clusterCellSecondMinVoltagePackIndex',
      hideInSearch: true,
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinSecondSmallestVoltagePacket' }), // 簇单体第二小电压包内索引
      dataIndex: 'clusterCellSecondMinVoltagePackInnerIndex',
      key: 'clusterCellSecondMinVoltagePackInnerIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.tmaxOfCluster' }), // 簇单体最大温度(℃)
      dataIndex: 'clusterCellMaxTemperature',
      key: 'clusterCellMaxTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfTmaxPacketForCluster' }), // 簇单体最大温度包索引
      dataIndex: 'clusterCellMaxTemperaturePackIndex',
      key: 'clusterCellMaxTemperaturePackIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinTmaxPackageOfClusterCells' }), // 簇单体最大温度包内索引
      dataIndex: 'clusterCellMaxTemperaturePackInnerIndex',
      key: 'clusterCellMaxTemperaturePackInnerIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.secondLargestTempOfCluster' }), // 簇单体第二大温度(℃)
      dataIndex: 'clusterCellSecondMaxTemperature',
      key: 'clusterCellSecondMaxTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfSecondLargestTempPacket' }), // 簇单体第二大温度包索引
      dataIndex: 'clusterCellSecondMaxTemperaturePackIndex',
      key: 'clusterCellSecondMaxTemperaturePackIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinSecondLargestTempPacket' }), // 簇单体第二大温度包内索引
      dataIndex: 'clusterCellSecondMaxTemperaturePackInnerIndex',
      key: 'clusterCellSecondMaxTemperaturePackInnerIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.tminOfCluster' }), // 簇单体最小温度(℃)
      dataIndex: 'clusterCellMinTemperature',
      key: 'clusterCellMinTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfTminPacketForCluster' }), // 簇单体最小温度包索引
      dataIndex: 'clusterCellMinTemperaturePackIndex',
      key: 'clusterCellMinTemperaturePackIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinTminPacketOfClusterCells' }), // 簇单体最小温度包内索引
      dataIndex: 'clusterCellMinTemperaturePackInnerIndex',
      key: 'clusterCellMinTemperaturePackInnerIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.secondSmallestTempOfCluster' }), // 簇单体第二小温度(℃)
      dataIndex: 'clusterCellSecondMinTemperature',
      key: 'clusterCellSecondMinTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.indexOfSecondSmallestTempPacket' }), // 簇单体第二小温度包索引
      dataIndex: 'clusterCellSecondMinTemperaturePackIndex',
      key: 'clusterCellSecondMinTemperaturePackIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.indexWithinSecondSmallestTempPacket' }), // 簇单体第二小温度包内索引
      dataIndex: 'clusterCellSecondMinTemperaturePackInnerIndex',
      key: 'clusterCellSecondMinTemperaturePackInnerIndex',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.voltage' }), // 电压(V)
      dataIndex: 'voltage',
      key: 'voltage',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.current' }), // 电流(A)
      dataIndex: 'current',
      key: 'current',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.power' }), // 功率(kW)
      dataIndex: 'power',
      key: 'power',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.soc' }), // SOC(%)
      dataIndex: 'soc',
      key: 'soc',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.soh' }), // SOH(%)
      dataIndex: 'soh',
      key: 'soh',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.soe' }), // SOE(%)
      dataIndex: 'soe',
      key: 'soe',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.sop' }), // SOP(%)
      dataIndex: 'sop',
      key: 'sop',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.sof' }), // SOF(%)
      dataIndex: 'sof',
      key: 'sof',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.positiveResistanceToGround' }), // 正对地电阻(Ω)
      dataIndex: 'positiveGroundResistance',
      key: 'positiveGroundResistance',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.negativeResistanceToGround' }), // 负对地电阻(Ω)
      dataIndex: 'negativeGroundResistance',
      key: 'negativeGroundResistance',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.dischargeableCapacity' }), // 可放电量(kWh)
      dataIndex: 'dischargeCapacity',
      key: 'dischargeCapacity',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.chargeableCapacity' }), // 可充电量(kWh)
      dataIndex: 'chargeCapacity',
      key: 'chargeCapacity',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.dailyTotalChargingCapacity' }), // 日累计充电电量(kWh)
      dataIndex: 'dailyChargeEnergy',
      key: 'dailyChargeEnergy',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.dailyTotalDischargeCapacity' }), // 日累计放电电量(kWh)
      dataIndex: 'dailyDischargeEnergy',
      key: 'dailyDischargeEnergy',
      hideInSearch: true,
      width: 200,
    },
    {
      title: intl.formatMessage({ id: 'data.totalChargeAH' }), // 累计充电(AH)
      dataIndex: 'totalChargeAH',
      key: 'totalChargeAH',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalDischargeAH' }), // 累计放电(AH)
      dataIndex: 'totalDischargeAH',
      key: 'totalDischargeAH',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalCharge' }), // 累计充电电量(kWh)
      dataIndex: 'totalChargeEnergy',
      key: 'totalChargeEnergy',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.totalDischarge' }), // 累计放电电量(kWh)
      dataIndex: 'totalDischargeEnergy',
      key: 'totalDischargeEnergy',
      hideInSearch: true,
      width: 150,
    },
  ];

  const [columns, setColumns] = useState<ProColumns[]>(clusterColumns);

  const fetchData = async (params: {
    current: number;
    pageSize: number;
    startDate: string;
    endDate: string;
  }) => {
    setLoading(true);
    const balance_mode_mapping = {
      '0': intl.formatMessage({ id: 'data.closure' }),
      '1': intl.formatMessage({ id: 'data.auto' }),
      '2': intl.formatMessage({ id: 'data.manual' }),
    };
    // 风扇状态
    const fs_mode_mapping = {
      1: intl.formatMessage({ id: 'data.run' }),
      0: intl.formatMessage({ id: 'data.unrun' }),
    };
    // 风扇故障
    const fsfault_mode_mapping = {
      '1': intl.formatMessage({ id: 'data.fault' }),
      '0': intl.formatMessage({ id: 'data.normal' }),
    };
    const response = await historyDataControllerClusterHistoryData({
      current: String(params.current),
      pageSize: String(params.pageSize),
      startDate: params.startDate,
      endDate: params.endDate,
      deviceCode,
      deviceType,
      areaId,
      correct: params.correct,
    });

    if (response.success && response.data && response.data?.records) {
      const records = response.data.records.map((record, index) => ({
        pageIndex: (params.current - 1) * params.pageSize + index + 1,
        collectTime: record.collectTime,
        reportTime: record.reportTime,
        correct: record.correct,
        batteryBoxName: record.boxName,
        batteryStackName: record.bmsName,
        batteryClusterName: record.clusterName,
        // @ts-ignore
        bcmsOnlineStatus: record.bcmsOnlineStatus,
        // @ts-ignore
        bcuOnlineStatus: record.bcuOnlineState,
        chargeDischargeStatus: record.bcSysState,
        contactorStatus: record.brkState
          ? record.brkState === '1'
            ? intl.formatMessage({ id: 'data.close' })
            : intl.formatMessage({ id: 'data.disconnect' })
          : record.brkState,
        totalBreakerFault: record.mainBreakerState
          ? record.mainBreakerState === '0'
            ? intl.formatMessage({ id: 'data.closure' })
            : intl.formatMessage({ id: 'data.open' })
          : record.mainBreakerState,
        // @ts-ignore
        balanceMode: balance_mode_mapping[record.balanceMode],
        balanceManualModeEnable: record.balanceManualModeEn
          ? record.balanceManualModeEn === '1'
            ? intl.formatMessage({ id: 'data.enable' })
            : intl.formatMessage({ id: 'data.disability' })
          : record.balanceManualModeEn,
        // balanceStatus: record.balanceState
        //   ? record.balanceState === '1'
        //     ? intl.formatMessage({ id: 'data.balancing' })
        //     : intl.formatMessage({ id: 'data.unbalanced' })
        //   : record.balanceState,
        // @ts-ignore
        fanStatus: fs_mode_mapping[record.fanState],
        // @ts-ignore
        fanFault: fsfault_mode_mapping[record.fanFault],
        powerLimitStatus: record.limitPowerState,
        alarmStatus: record.warnState,
        protectionStatus: record.prtState,
        chargePowerLimit: record.limitChgPower,
        dischargePowerLimit: record.limitDchgPower,
        clusterBMUAverageVoltage: record.bmuAvgVol,
        clusterCellAverageVoltage: record.cellAvgVol,
        clusterCellAverageTemperature: record.cellAvgTemp,
        clusterCellMaxVoltageDifference: record.volDifMax,
        clusterCellMaxTemperatureDifference: record.tempDifMax,
        clusterCellMaxVoltage: record.vmax,
        clusterCellMaxVoltagePackIndex: record.vmaxBmuIdx,
        clusterCellMaxVoltagePackInnerIndex: record.vmaxCellIdx,
        clusterCellSecondMaxVoltage: record.vmaxSec,
        clusterCellSecondMaxVoltagePackIndex: record.vmaxSecBmuIdx,
        clusterCellSecondMaxVoltagePackInnerIndex: record.vmaxSecCellIdx,
        clusterCellMinVoltage: record.vmin,
        clusterCellMinVoltagePackIndex: record.vminBmuIdx,
        clusterCellMinVoltagePackInnerIndex: record.vminCellIdx,
        clusterCellSecondMinVoltage: record.vminSec,
        clusterCellSecondMinVoltagePackIndex: record.vminSecBmuIdx,
        clusterCellSecondMinVoltagePackInnerIndex: record.vminSecCellIdx,
        clusterCellMaxTemperature: record.tmax,
        clusterCellMaxTemperaturePackIndex: record.tmaxBmuIdx,
        clusterCellMaxTemperaturePackInnerIndex: record.tmaxCellIdx,
        clusterCellSecondMaxTemperature: record.tmaxSec,
        clusterCellSecondMaxTemperaturePackIndex: record.tmaxSecBmuIdx,
        clusterCellSecondMaxTemperaturePackInnerIndex: record.tmaxSecCellIdx,
        clusterCellMinTemperature: record.tmin,
        clusterCellMinTemperaturePackIndex: record.tminBmuIdx,
        clusterCellMinTemperaturePackInnerIndex: record.tminCellIdx,
        clusterCellSecondMinTemperature: record.tminSec,
        clusterCellSecondMinTemperaturePackIndex: record.tminSecBmuIdx,
        clusterCellSecondMinTemperaturePackInnerIndex: record.tminSecCellIdx,
        voltage: record.voltage,
        current: record.current,
        power: record.power,
        soc: record.soc,
        soh: record.soh,
        soe: record.soe,
        sop: record.sop,
        sof: record.sof,
        positiveGroundResistance: record.pbusResistor,
        negativeGroundResistance: record.nbusResistor,
        dischargeCapacity: record.leftEnergy,
        chargeCapacity: record.usedEnergy,
        dailyChargeEnergy: record.dayInputWatt,
        dailyDischargeEnergy: record.dayOutputWatt,
        totalChargeAH: record.inputAH,
        totalDischargeAH: record.outputAH,
        totalChargeEnergy: record.inputWatt,
        totalDischargeEnergy: record.outputWatt,
      }));
      // @ts-ignore
      setData(records);
      // @ts-ignore
      setTotal(response.data.total);
      // 筛选需要隐藏的列
      const hiddenColumnKeys = getHiddenColumnKeysFromRecords(records);
      const updatedColumns = hideEmptyDataColumns(columns, hiddenColumnKeys);
      setColumns(updatedColumns);
    } else {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData(params);
  }, [deviceCode, deviceType, areaId, params]);

  const handleTableChange = (pagination: { current: number; pageSize: number }) => {
    setParams((prevParams) => ({
      ...prevParams,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));
  };

  const handleSearch = (values: any) => {
    const startDate = dayjs(values.startDate);
    const endDate = dayjs(values.endDate);
    if (endDate.diff(startDate, 'day') > 31) {
      message.warning(intl.formatMessage({ id: 'data.sDays' }));
      return;
    }
    setParams((prevParams) => ({
      ...prevParams,
      startDate: values.startDate,
      endDate: values.endDate,
      correct: values.correct,
    }));
  };

  const handleReset = () => {
    setParams({
      current: 1,
      pageSize: 20,
      startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
      endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
      correct: undefined,
    });
    fetchData(params);
  };

  const scroll = {
    x: 'max-content',
    y: 'calc(100vh - 300px)',
  };

  const columnToAttrMap: Record<string, string> = {
    // 基础信息
    collectTime: 'collectTime', // 采集时间
    reportTime: 'reportTime', // 上报时间
    correct: 'correct', // 数据有效性
    batteryBoxName: 'boxName', // 电池箱名称
    batteryStackName: 'bmsName', // 电池堆名称
    batteryClusterName: 'clusterName', // 电池簇名称

    // 状态信息
    bcmsOnlineStatus: 'bcmsOnlineStatus', // BCMS在线状态
    bcuOnlineStatus: 'bcuOnlineState', // BCU在线状态
    chargeDischargeStatus: 'bcSysState', // 充放电状态
    contactorStatus: 'brkState', // 接触器状态
    totalBreakerFault: 'mainBreakerState', // 总断路器故障
    balanceMode: 'balanceMode', // 均衡模式
    balanceManualModeEnable: 'balanceManualModeEn', // 均衡手动模式使能
    // balanceStatus: 'balanceState', // 均衡状态
    fanStatus: 'fanState', // 风扇状态
    fanFault: 'fanFault', // 风扇故障
    powerLimitStatus: 'limitPowerState', // 限功率状态字
    alarmStatus: 'warnState', // 告警状态字
    protectionStatus: 'prtState', // 保护状态字

    // 功率限值
    chargePowerLimit: 'limitChgPower', // 充电功率限值
    dischargePowerLimit: 'limitDchgPower', // 放电功率限值

    // 电压相关
    clusterBMUAverageVoltage: 'bmuAvgVol', // 簇BMU平均电压
    clusterCellAverageVoltage: 'cellAvgVol', // 簇单体平均电压
    clusterCellMaxVoltageDifference: 'volDifMax', // 簇单体最大压差
    clusterCellMaxVoltage: 'vmax', // 簇单体最大电压
    clusterCellMaxVoltagePackIndex: 'vmaxBmuIdx', // 簇单体最大电压包索引
    clusterCellMaxVoltagePackInnerIndex: 'vmaxCellIdx', // 簇单体最大电压包内索引
    clusterCellSecondMaxVoltage: 'vmaxSec', // 簇单体第二大电压
    clusterCellSecondMaxVoltagePackIndex: 'vmaxSecBmuIdx', // 簇单体第二电压包索引
    clusterCellSecondMaxVoltagePackInnerIndex: 'vmaxSecCellIdx', // 簇单体第二电压包内索引
    clusterCellMinVoltage: 'vmin', // 簇单体最小电压
    clusterCellMinVoltagePackIndex: 'vminBmuIdx', // 簇单体最小电压包索引
    clusterCellMinVoltagePackInnerIndex: 'vminCellIdx', // 簇单体最小电压包内索引
    clusterCellSecondMinVoltage: 'vminSec', // 簇单体第二小电压
    clusterCellSecondMinVoltagePackIndex: 'vminSecBmuIdx', // 簇单体第二小电压包索引
    clusterCellSecondMinVoltagePackInnerIndex: 'vminSecCellIdx', // 簇单体第二小电压包内索引

    // 温度相关
    clusterCellAverageTemperature: 'cellAvgTemp', // 簇单体平均温度
    clusterCellMaxTemperatureDifference: 'tempDifMax', // 簇单体最大温差
    clusterCellMaxTemperature: 'tmax', // 簇单体最大温度
    clusterCellMaxTemperaturePackIndex: 'tmaxBmuIdx', // 簇单体最大温度包索引
    clusterCellMaxTemperaturePackInnerIndex: 'tmaxCellIdx', // 簇单体最大温度包内索引
    clusterCellSecondMaxTemperature: 'tmaxSec', // 簇单体第二大温度
    clusterCellSecondMaxTemperaturePackIndex: 'tmaxSecBmuIdx', // 簇单体第二大温度包索引
    clusterCellSecondMaxTemperaturePackInnerIndex: 'tmaxSecCellIdx', // 簇单体第二大温度包内索引
    clusterCellMinTemperature: 'tmin', // 簇单体最小温度
    clusterCellMinTemperaturePackIndex: 'tminBmuIdx', // 簇单体最小温度包索引
    clusterCellMinTemperaturePackInnerIndex: 'tminCellIdx', // 簇单体最小温度包内索引
    clusterCellSecondMinTemperature: 'tminSec', // 簇单体第二小温度
    clusterCellSecondMinTemperaturePackIndex: 'tminSecBmuIdx', // 簇单体第二小温度包索引
    clusterCellSecondMinTemperaturePackInnerIndex: 'tminSecCellIdx', // 簇单体第二小温度包内索引

    // 电气参数
    voltage: 'voltage', // 电压
    current: 'current', // 电流
    power: 'power', // 功率
    soc: 'soc', // SOC
    soh: 'soh', // SOH
    soe: 'soe', // SOE
    sop: 'sop', // SOP
    sof: 'sof', // SOF

    // 接地电阻
    positiveGroundResistance: 'pbusResistor', // 正对地电阻
    negativeGroundResistance: 'nbusResistor', // 负对地电阻

    // 容量相关
    dischargeCapacity: 'leftEnergy', // 可放电量
    chargeCapacity: 'usedEnergy', // 可充电量
    dailyChargeEnergy: 'dayInputWatt', // 日累计充电电量
    dailyDischargeEnergy: 'dayOutputWatt', // 日累计放电电量
    totalChargeAH: 'inputAH', // 累计充电AH
    totalDischargeAH: 'outputAH', // 累计放电AH
    totalChargeEnergy: 'inputWatt', // 累计充电电量
    totalDischargeEnergy: 'outputWatt', // 累计放电电量
  };

  const exportDataReportFun = async (params: any) => {
    const startDate = dayjs(params.startDate);
    const endDate = dayjs(params.endDate);
    if (endDate.diff(startDate, 'day') > 3) {
      message.warning(intl.formatMessage({ id: 'data.selectTimeRange' }));
      return;
    }

    // 获取当前表格中非空的列
    const nonEmptyColumns = columns
      .filter((col) => {
        // 跳过索引列
        if (col.dataIndex === 'index' || col.dataIndex === 'pageIndex') {
          return false;
        }

        // 检查该列是否在所有数据中都为null
        const isAllNull = data.every((record) => {
          const value = record[col.dataIndex as string];
          return value === null || value === undefined;
        });

        return !isAllNull;
      })
      .map((col) => col.dataIndex as string);

    // 根据非空列获取对应的属性名
    const attrNames =
      selectedColumns.length > 0
        ? selectedColumns
            .filter(
              (col) => col !== 'index' && col !== 'pageIndex' && nonEmptyColumns.includes(col),
            )
            .map((col) => columnToAttrMap[col] || col)
        : nonEmptyColumns.map((col) => columnToAttrMap[col] || col);

    const exportParams: API.HistoryDataQuery = {
      areaId: Number(areaId),
      deviceType,
      deviceCode,
      startDate: dayjs(params.startDate).format('YYYY-MM-DD HH:mm:ss'),
      endDate: dayjs(params.endDate).format('YYYY-MM-DD HH:mm:ss'),
      attrNames,
    };

    await downloadFetch(exportDataReport, exportParams);
  };

  return (
    <div>
      <ProTable
        headerTitle={intl.formatMessage({ id: 'data.clusterInformation' })} // 电池簇信息
        search={{
          labelWidth: 80,
        }}
        columns={columns}
        scroll={scroll}
        pagination={{
          current: params.current,
          pageSize: params.pageSize,
          total,
          onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
        }}
        dataSource={data}
        loading={loading}
        onSubmit={handleSearch}
        onReset={handleReset}
        toolbar={{
          className: 'historyToobalr',
          actions: [
            <>
              <HandleBtn
                key="export"
                handleType="export"
                onClick={() => exportDataReportFun(params)}
              >
                {intl.formatMessage({ id: 'statistics.common.export' })}
              </HandleBtn>
              <Link key="monitor" to={`/stationmonitor/realtime?key=${selectedKeys}`}>
                {intl.formatMessage({ id: 'data.realtimeMonitor' })}
              </Link>
            </>,
          ],
        }}
        columnsState={{
          value: Object.fromEntries(
            columns
              .filter((col) => col.dataIndex)
              .map((col) => [
                col.dataIndex,
                {
                  show:
                    selectedColumns.length === 0
                      ? true
                      : selectedColumns.includes(col.dataIndex as string),
                },
              ]),
          ),
          onChange: (stateMap) => {
            const newSelectedColumns = Object.entries(stateMap)
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              .filter(([_, value]) => value.show)
              .map(([key]) => key);
            setSelectedColumns(newSelectedColumns);
          },
          persistenceKey: 'battery-cluster-info-columns', // 添加持久化key
          persistenceType: 'localStorage', // 持久化类型
        }}
      />
    </div>
  );
};

export default BatteryClusterInfo;
